package st.business.tepth.business.goods;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.jakewharton.rxbinding2.widget.RxTextView;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;
import st.business.tepth.R;
import st.business.tepth.R2;
import st.business.tepth.business.bean.ConsumableBean;
import st.business.tepth.business.bean.ConsumableSearchBean;
import st.business.tepth.business.bean.post.IDBean;
import st.business.tepth.business.goodsorder.GoodsOrderDelegate;
import st.business.tepth.business.goodsreceive.GoodsReceiveDelegate;
import st.business.tepth.config.Url;
import st.business.tepth.manager.UserManager;
import st.business.tepth.view.ClearEditText;
import st.shadow.library.core.base.mvp.MvpFragment;
import st.shadow.library.core.net.data.ObjConverter;
import st.shadow.library.core.net.rx.RxRestClient;
import st.shadow.library.ui.dialog.DialogLoader;
import st.shadow.library.ui.dialog.IDialogClickListener;
import st.shadow.library.ui.recycler.BaseDecoration;
import st.shadow.library.ui.snacktop.TSnackbar;

/**
 * Author: shadow
 * Email:  1025431817@qq.com
 * Time:   2019-02-25 15:38
 * 耗材搜索
 */

public class GoodsDelegate extends MvpFragment<GoodsPresenter> implements GoodsContract.View {
    public static GoodsDelegate newInstance() {
        return new GoodsDelegate();
    }

    @BindView(R2.id.recycler_view_common)
    RecyclerView mRecyclerViewCommon;
    @BindView(R2.id.recycler_view_search_result)
    RecyclerView mRecyclerViewSearchResult;
    @BindView(R2.id.et_search)
    ClearEditText mClearEditText;
    @BindView(R2.id.layout_root)
    ConstraintLayout mLayoutRoot;
    @BindView(R2.id.tv_tile)
    TextView mTvTitle;
    @BindView(R2.id.view_diver)
    View mViewDiver;
    @BindView(R2.id.layout_coor)
    CoordinatorLayout mCoordinatorLayout;
    private DialogLoader mDialogLoader;
    private TSnackbar mSnackBar;
    private Disposable mDisposable;

    @Override
    public GoodsPresenter getPresenter() {
        return new GoodsPresenter(this);
    }

    @Override
    public Object setLayout() {
        return R.layout.delegate_goods_search;
    }

    @Override
    public void onBindView(@Nullable final Bundle savedInstanceState, View rootView) {
        mTvTitle.setText("耗材");
        mDialogLoader = new DialogLoader(_mActivity);
        mRecyclerViewCommon.setLayoutManager(new LinearLayoutManager(_mActivity));
        mRecyclerViewCommon.addOnItemTouchListener(new OnItemChildClickListener() {
            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter adapter, View view,
                                               int position) {
                ConsumableBean consumableBean = (ConsumableBean) adapter.getItem(position);
                if (consumableBean != null) {
                    if (view.getId() == R.id.tv_add_to_apply) {
                        //加入待领料
                        List<WaiteApply> list = new ArrayList<>();
                        list.add(new WaiteApply(consumableBean.getId(),
                                2, 1));
                        mPresenter.waiteApply(UserManager.getInstance().getToken(),
                                JSON.toJSONString(list));
                    } else if (view.getId() == R.id.tv_apply_goods) {
                        List<IDBean> list = new ArrayList<>();
                        list.add(new IDBean(consumableBean.getId()));
                        mPresenter.applyGoods(UserManager.getInstance().getToken(),
                                JSON.toJSONString(list));
                        mDialogLoader.showProgressDialog(true,
                                "正在提交", "请稍候...");
                    }
                }
            }
        });
        mRecyclerViewSearchResult.setLayoutManager(new LinearLayoutManager(_mActivity));
        GoodsAdapter commonAdapter = new GoodsAdapter(R.layout.item_goods_search, null);
        commonAdapter.addHeaderView(LayoutInflater.
                from(_mActivity).inflate(R.layout.item_head_goods,
                null));
        mRecyclerViewCommon.setAdapter(commonAdapter);
        mRecyclerViewCommon.addItemDecoration(BaseDecoration.
                create(Color.parseColor("#f0f0f0"), 1));

        final GoodsAdapter searchPartAdapter =
                new GoodsAdapter(R.layout.item_goods_search, null);
        searchPartAdapter.setEmptyView(R.layout.view_search_empty,
                (ViewGroup) mRecyclerViewSearchResult.getParent());
        mRecyclerViewSearchResult.setAdapter(searchPartAdapter);
        mRecyclerViewSearchResult.addItemDecoration(BaseDecoration.
                create(Color.parseColor("#f0f0f0"), 1));
        mRecyclerViewSearchResult.addOnItemTouchListener(new OnItemChildClickListener() {
            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter adapter, View view,
                                               int position) {
                ConsumableBean consumableBean = (ConsumableBean) adapter.getItem(position);
                if (consumableBean != null) {
                    if (view.getId() == R.id.tv_add_to_apply) {
                        //加入待领料
                        List<WaiteApply> list = new ArrayList<>();
                        list.add(new WaiteApply(consumableBean.getId(),
                                2, 1));
                        mPresenter.waiteApply(UserManager.getInstance().getToken(),
                                JSON.toJSONString(list));
                    } else if (view.getId() == R.id.tv_apply_goods) {
                        List<WaiteApply> list = new ArrayList<>();
                        list.add(new WaiteApply(consumableBean.getId(),
                                2, 1));
                        mPresenter.applyGoods(UserManager.getInstance().getToken(),
                                JSON.toJSONString(list));
                        mDialogLoader.showProgressDialog(true,
                                "正在提交", "请稍候...");
                    }
                }
            }
        });
        Observer observable = RxTextView.textChanges(mClearEditText)
                .subscribeOn(AndroidSchedulers.mainThread())
                .debounce(600, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread())
                .filter(new Predicate<CharSequence>() {
                    @Override
                    public boolean test(CharSequence charSequence) throws Exception {
                        if (charSequence.length() == 0) {
                            mRecyclerViewSearchResult.setVisibility(View.GONE);
                        } else {
                            mRecyclerViewSearchResult.setVisibility(View.VISIBLE);
                        }
                        return charSequence.length() > 0;
                    }
                })
                .switchMap(new Function<CharSequence, Observable<String>>() {
                    @Override
                    public Observable<String> apply(CharSequence charSequence) throws Exception {
                        return RxRestClient.builder()
                                .url(Url.GetConsumableList)
                                .params("token", UserManager.getInstance().getToken())
                                .params("pageNumber", 1)
                                .params("pageSize", 30)
                                .params("materialName", charSequence.toString())
                                .build()
                                .onlyPost();
                    }
                })
                .subscribeWith(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        mDisposable = d;
                    }

                    @Override
                    public void onNext(String response) {
                        JSONObject jsonObject = JSONObject.parseObject(response);
                        int ResultCode = jsonObject.getInteger("code");
                        String object = jsonObject.getString("data");
                        String ResultMsg = jsonObject.getString("msg");
                        ConsumableSearchBean searchBean =
                                new ObjConverter<ConsumableSearchBean>().convert(object
                                        , new TypeReference<ConsumableSearchBean>() {
                                        });
                        // recyclerViewResult.setVisibility(View.VISIBLE);
                        if (searchBean != null) {
                            searchPartAdapter.setNewData(searchBean.getList());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
        initSnackBar();
    }

    @OnClick({R2.id.tv_back})
    public void onBack() {
        pop();
    }

    private void initSnackBar() {
        //加入待领料
        mSnackBar = TSnackbar.make(mCoordinatorLayout,
                R.string._action, TSnackbar.LENGTH_SHORT);
        TSnackbar.SnackbarLayout snackBarLayout =
                (TSnackbar.SnackbarLayout) mSnackBar.getView();
        snackBarLayout.setBackgroundColor(Color.parseColor("#00000000"));
        View customView = LayoutInflater.from(_mActivity).inflate
                (R.layout.view_snakebar_add_to_apply, null);
        customView.findViewById(R.id.tv_action).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                start(GoodsReceiveDelegate.newInstance());
            }
        });
        snackBarLayout.addView(customView,
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT);
    }

    @Override
    public void showError(String msg) {
        mDialogLoader.stopProgressWithFailed(msg, msg);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mDisposable != null) {
            mDisposable.dispose();
        }
    }

    @Override
    public void showApplySucceed() {
        mDialogLoader.stopProgressWithSuccess("提交成功", "可以领料单中查看", new IDialogClickListener() {
            @Override
            public void onClick() {
                mDialogLoader.clearDialog();
                start(GoodsOrderDelegate.newInstance(0));
            }
        });
        mDialogLoader.setConfirmText("领料单");
        mDialogLoader.setCancelText("关闭");
        mDialogLoader.showCancel(true);
    }

    @Override
    public void showWaiteApplySucceed() {
        if (mSnackBar != null) {
            mSnackBar.show();
        }
    }

    public class WaiteApply {
        private int parts_id;
        private int parts_type;
        private int apply_amount;

        public WaiteApply() {
        }

        public WaiteApply(int parts_id, int parts_type, int apply_amount) {
            this.parts_id = parts_id;
            this.parts_type = parts_type;
            this.apply_amount = apply_amount;
        }

        public int getParts_id() {
            return parts_id;
        }

        public void setParts_id(int parts_id) {
            this.parts_id = parts_id;
        }

        public int getParts_type() {
            return parts_type;
        }

        public void setParts_type(int parts_type) {
            this.parts_type = parts_type;
        }

        public int getApply_amount() {
            return apply_amount;
        }

        public void setApply_amount(int apply_amount) {
            this.apply_amount = apply_amount;
        }
    }
}